/**
 * Store核心实现 - 类似Pinia
 */
import { PersistUtil } from './persist'
import { StoreOptions, StoreDefinition, PersistOptions } from './types'

// 存储所有store实例
const storeMap = new Map<string, any>()

/**
 * 定义Store
 */
export function defineStore<S extends object, G extends object, A extends object>(
  options: StoreOptions<S, G, A>
): StoreDefinition<S, G, A> {
  const { id, state: stateFn, getters = {} as G, actions = {} as A, persist } = options
  
  return (): any => {
    // 如果store已存在，直接返回
    if (storeMap.has(id)) {
      return storeMap.get(id)
    }
    
    // 创建store实例
    const store = createStore(id, stateFn, getters as any, actions as any, persist)
    storeMap.set(id, store)
    
    return store
  }
}

/**
 * 创建Store实例
 */
function createStore<S extends object, G extends object, A extends object>(
  id: string,
  stateFn: () => S,
  getters: G,
  actions: A,
  persist?: PersistOptions
) {
  // 初始化状态
  let initialState = stateFn()
  
  // 如果启用持久化，从本地加载
  if (persist?.enabled) {
    const persistKey = persist.key || `store_${id}`
    loadPersistedState(persistKey, initialState).then(loadedState => {
      if (loadedState) {
        Object.assign(state, loadedState)
      }
    })
  }
  
  // 创建响应式状态对象
  const state = { ...initialState }
  
  // 创建store对象
  const store: any = {
    $id: id,
    $state: state,
    
    // 重置状态
    $reset: () => {
      const newState = stateFn()
      Object.keys(state).forEach(key => {
        delete state[key]
      })
      Object.assign(state, newState)
      
      // 如果启用持久化，清除本地数据
      if (persist?.enabled) {
        const persistKey = persist.key || `store_${id}`
        PersistUtil.remove(persistKey)
      }
    },
    
    // 批量更新状态
    $patch: (partialState: Partial<S>) => {
      Object.assign(state, partialState)
      
      // 持久化
      if (persist?.enabled) {
        const persistKey = persist.key || `store_${id}`
        savePersistedState(persistKey, state, persist)
      }
    }
  }
  
  // 添加state到store（支持直接访问）
  Object.keys(state).forEach(key => {
    Object.defineProperty(store, key, {
      get: () => state[key],
      set: (value) => {
        state[key] = value
        
        // 持久化
        if (persist?.enabled) {
          const persistKey = persist.key || `store_${id}`
          savePersistedState(persistKey, state, persist)
        }
      },
      enumerable: true,
      configurable: true
    })
  })
  
  // 添加getters到store
  Object.keys(getters).forEach(key => {
    const getter = (getters as any)[key]
    Object.defineProperty(store, key, {
      get: () => {
        if (typeof getter === 'function') {
          return getter.call(store, state)
        }
        return getter
      },
      enumerable: true,
      configurable: true
    })
  })
  
  // 添加actions到store
  Object.keys(actions).forEach(key => {
    const action = (actions as any)[key]
    store[key] = function (...args: any[]) {
      const result = action.apply(store, args)
      
      // action执行后持久化
      if (persist?.enabled) {
        const persistKey = persist.key || `store_${id}`
        savePersistedState(persistKey, state, persist)
      }
      
      return result
    }
  })
  
  return store
}

/**
 * 保存持久化状态
 */
async function savePersistedState(key: string, state: any, persist?: PersistOptions) {
  try {
    let dataToSave = state
    
    // 如果指定了paths，只保存指定的字段
    if (persist?.paths && persist.paths.length > 0) {
      dataToSave = {}
      persist.paths.forEach(path => {
        if (state.hasOwnProperty(path)) {
          dataToSave[path] = state[path]
        }
      })
    }
    
    await PersistUtil.set(key, dataToSave)
  } catch (err) {
    console.error(`保存store失败: ${key}`, err)
  }
}

/**
 * 加载持久化状态
 */
async function loadPersistedState(key: string, defaultState: any): Promise<any> {
  try {
    return await PersistUtil.get(key, defaultState)
  } catch (err) {
    console.error(`加载store失败: ${key}`, err)
    return null
  }
}

/**
 * 获取store实例
 */
export function getStore<T>(id: string): T | undefined {
  return storeMap.get(id)
}

/**
 * 清除所有store
 */
export function clearAllStores() {
  storeMap.clear()
}

// 导出类型
export * from './types'
export { PersistUtil } from './persist'

// 不要在这里导出 store 模块，避免循环依赖
// 使用者应该从 './modules/index' 或 './modules/user'、'./modules/chat' 直接导入

